/*
 * TestHttpServer.cpp
 *
 *   Created on: 2010-2-11
 *  Description: 
 *    Copyright: 2010 @ ICT Li Heyuan
 */

#include "../include/json_cpp/value.h"
using Json::Value;

#include "../include/server/HttpServer.h"
#include "../include/method/RpcMethod.h"
#include "../include/util/Util.h"

#include <unistd.h>
#include <sys/types.h>
#include <signal.h>

#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;

class AddMethod2: public RpcMethod
{

	bool execute_logic(Value &param, Value& retVal, const EasyAddr &addr,
			string& error)
	{
		try
		{
			unsigned int index = 0;

			unsigned int a = param[index].asUInt();
			index++;
			unsigned int b = param[index].asUInt();
			//返回值
			retVal = Value(a + b);

			return true;
		} catch (...)
		{
			return false;
		}
	}
};

void test2()
{
	HttpServer server(18080);
	server.addMethod("add", new AddMethod2());

	if (!server.init())
	{
		exit(-1);
	}

	server.service();
}

void client2()
{
	int sock = Network::socket();
	EasyAddr addr;
	addr.ip = "10.23.0.148";
	addr.port = 8080;

	//Network::setNonBlocking(sock);

	if (!Network::connect(sock, addr))
	{
		cout << "连接失败:" << Util::getInstance()->getErrMsg() << endl;
		exit(-1);
	}

	//生成1000个随机字母
	std::string send(1000, 'a');

	std::string read;
	unsigned long nSend = send.length();
	bool eof = false;
	//写入 & 读取
	while (!eof)
	{
		//先写
		if (nSend && !Network::sendBytes(sock, send, nSend))
		{
			//写入失败
			cout << "写入失败" << endl;
		}
		else
		{
			//cout << "写入成功，剩余" << nSend << "字节" << endl;
		}

		//再读取
		if (!Network::recvBytes(sock, read, eof))
		{
			cout << "读取失败" << endl;
		}
		else
		{
			//cout << "读取成功，目前" << read.size() << "字节" << endl;
		}

		if (read.size() == 1000)
		{
			Network::close(sock);
			break;
		}
	}

	if (send == read)
	{
		cout << "1000个随机字母测试成功" << endl;
	}
	else
	{
		cout << "1000个随机字母测试失败" << endl;
		/*cout << "收到的是:" << read << endl;*/
	}
}
/*

 int main()
 {

 test2();

 }

 */
